package com.yuliang.utils.util;

import com.alibaba.fastjson.JSONObject;

import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Huangkai
 */
public class UnicodeConvert {

    public static Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
    /**
     * @Title: unicodeEncode
     * @Description: unicode编码
     * @param string
     * @return
     */
    public static String unicodeEncode(String string) {
        char[] utfBytes = string.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * Unicode转中文
     * @Title: unicodeDecode
     * @Description: unicode解码
     * @param
     * @return
     */
    public static String unicodeDecode(String string) {
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    public static void main(String[] args) {
        /*
        String sourceData = "这是原始的数据！！！";
        String unicodeEncode = unicodeEncode(sourceData);
        System.out.println("编码结果：");
        System.out.println(unicodeEncode);//\u8fd9\u662f\u539f\u59cb\u7684\u6570\u636e\uff01\uff01\uff01

        String unicodeDecode = unicodeDecode(unicodeEncode);
        System.out.println("解码结果：");
        System.out.println(unicodeDecode);//这是原始的数据！！！

         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceId", "c439de03a9d1406ab29ade8bf76b97c2");
        String t = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
        System.out.println(t);

        String content= "请生成一个桂林风景的视频";
         t = Base64.getEncoder().encodeToString(content.getBytes());
        System.out.println(t);

    }
}
